package com.eflow.model.flowable;

import com.eflow.model.flowable.utils.BaseEnumUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * @author hui se
 * @description
 * @create 2021-03-05 17:56
 **/
@Data
public class CommonDeserializer extends JsonDeserializer<Enum> implements ContextualDeserializer {
    private Class clz;
    @Override
    public Enum deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
        if(StringUtils.isEmpty(jsonParser.getText())){
            return null;
        }
        if(BaseEnumUtil.isImplementsBaseEnum(clz)){
            return  BaseEnumUtil.convertToEnum(clz,jsonParser.getIntValue());
        }else {
            return null;
        }
    }

    /**
     * 获取合适的解析器，把当前解析的属性Class对象存起来，以便反序列化的转换类型，为了避免线程安全问题，每次都new一个（通过threadLocal来存储更合理）
     * @param ctx
     * @param property
     * @return
     * @throws JsonMappingException
     */
    @Override
    public JsonDeserializer createContextual(DeserializationContext ctx, BeanProperty property) throws JsonMappingException {
        Class rawCls = ctx.getContextualType().getRawClass();
        CommonDeserializer clone = new CommonDeserializer();
        clone.setClz(rawCls);
        return clone;
    }
}
